package com.kaka.bus.engine.borrow.pact;

import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.kaka.bus.R;
import com.kaka.bus.base.BaseActivity;
import com.kaka.bus.bean.HttpWrapper;
import com.kaka.bus.constant.Constant;
import com.kaka.bus.engine.HomeActivity;
import com.kaka.bus.engine.result.ResultActivity;
import com.kaka.bus.util.U;
import com.kaka.bus.util.logger.Logger;
import com.kaka.bus.view.MutipleLayout;
import com.kaka.bus.view.dialog.MessageDialog;

import butterknife.BindView;

/**
 * Created by zhangqi on 2016/10/24.
 */

public class PactActivity extends BaseActivity<PactPresenter> implements PactContract.View {


    @BindView(R.id.toolbar_back)
    ImageView mToolbarBack;
    @BindView(R.id.toolbar_name)
    TextView mToolbarName;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.pact_progressbar)
    ProgressBar mPactProgressbar;
    @BindView(R.id.pact_webview)
    WebView mPactWebview;
    @BindView(R.id.pact_muti)
    MutipleLayout mPactMuti;
    public static String URL = "URL";
    private MessageDialog mDialog;

    @Override
    protected void initView() {
        super.initView();
        mToolbarBack.setOnClickListener(v -> finish());
        mToolbarName.setText("签约");

        mDialog = new MessageDialog(this);
        mDialog.setOnNormalDialogLeftListener(() -> {
            startActivity(new Intent(this, HomeActivity.class));
            finish();
        });

        U.initWebView(mPactWebview, mPactProgressbar);
    }

    @Override
    protected void initData() {
        mPresenter.getPactInfo(getUserId(), getToken(), Constant.PLATFORM);
        mPactWebview.addJavascriptInterface(new JSInterface(), "yhs");
    }

    class JSInterface {

        @JavascriptInterface
        public void callApp(String code) {
            runOnUiThread(() -> {
                if ("201".equals(code)) {
                    U.tokenOut(PactActivity.this);
                } else if ("200".equals(code)) {
                    startActivity(new Intent(PactActivity.this, HomeActivity.class));
                    finish();
                }
            });

        }

        @JavascriptInterface
        public void callOpen(String url) {
            runOnUiThread(() -> {
                runOnUiThread(() -> {
                    lookTheOpen(PactGreementActivity.TYPE_LOAD_URL, "手机出售及回购协议", "loan/agreement.action?per_id=" + getUserId());
                });
            });
        }

        /**
         * 用户授权协议
         *
         * @param url
         */
        @JavascriptInterface
        public void userAuthOpen(String url) {
            runOnUiThread(() -> {
                lookTheOpen(PactGreementActivity.TYPE_LOAD_URL, "用户授权协议", url);
            });
        }

        /**
         * 数字证书服务协议(e签宝)
         *
         * @param url
         */
        @JavascriptInterface
        public void certificateOpen(String url) {
            runOnUiThread(() -> {
                runOnUiThread(() -> {
                    lookTheOpen(PactGreementActivity.TYPE_LOAD_URL, "数字证书服务协议(e签宝)", "loan/numberPage.action?per_id=" + getUserId());
                });
            });
        }

        /**
         * 手机出售及回购协议
         *
         * @param url
         */
        @JavascriptInterface
        public void sellPhoneOpen(String url) {
            runOnUiThread(() -> {
                lookTheOpen(PactGreementActivity.TYPE_LOAD_URL, "手机出售及回购协议", url);
            });
        }

        /**
         * 签约
         *
         * @param perId
         * @param borrId
         */
        @JavascriptInterface
        public void callSign(String perId, String borrId) {
            /**
             * 必须要主线程 现在是在jsbridge线程
             */
            Logger.i("前去签约");
            runOnUiThread(() -> mPresenter.commitPact(perId, borrId, getToken()));
        }
    }

    @Override
    public void getPactInfoSuccess(String pact) {
        if (!TextUtils.isEmpty(pact)) {
            Logger.i(pact);
            mPactMuti.setStatus(MutipleLayout.Success);
            mPactWebview.loadDataWithBaseURL(null, pact, "text/html", "utf-8", null);
        } else {
            onFaild();
        }
    }


    @Override
    public void netError(Throwable e) {
        mPactMuti.setStatus(MutipleLayout.No_Network);
    }

    @Override
    public void pactSuccess(HttpWrapper<String> pact) {
        Logger.i("签约的信息" + new Gson().toJson(pact));
        if (Constant.SUCCESS_CODE.equals(pact.code)) {
            /**
             * 调用js方法通知js签约成功
             */
            Intent intent = new Intent(this, ResultActivity.class);
            intent.putExtra(ResultActivity.RESULT_TYPE, ResultActivity.WAIT);
            startActivity(intent);
            finish();
        } else if (Constant.TOKEN_TIMEOUT.equals(pact.code)) {
            U.tokenOut(this);
        } else if (Constant.ERROR_CODE.equals(pact.code)) {
            mDialog.show();
            mDialog.setMessage(pact.info);
        } else {
            showMessage(pact.getInfo());
        }
    }

    public void onFaild() {
        mPactMuti.setStatus(MutipleLayout.Error);
    }

    private void lookTheOpen(String type, String title, String url) {
        Intent intent = new Intent(PactActivity.this, PactGreementActivity.class);
        intent.putExtra(PactGreementActivity.TYPE, type);
        intent.putExtra(PactGreementActivity.TITLE, title);
        intent.putExtra(PactGreementActivity.URL, Constant.BASE_URL + url);
        startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pact;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }


}
